<template>
  <div class="app-container">
    <!-- 状态导航栏 -->
    <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
      <el-tab-pane label="全部" name=""></el-tab-pane>
      <el-tab-pane label="申请中" name="1"></el-tab-pane>
      <el-tab-pane label="已完成" name="2"></el-tab-pane>
      <el-tab-pane label="未通过" name="3"></el-tab-pane>
    </el-tabs>


    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主键id" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入主键id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="采购时间" prop="orderTime">
        <el-date-picker clearable v-model="queryParams.orderTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择采购时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="总金额" prop="amount">
        <el-input v-model="queryParams.amount" placeholder="请输入总金额" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态，1 申请中，2 已完成，3 未通过" clearable>
          <el-option v-for="dict in sys_orders_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['orders:orders:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['orders:orders:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['orders:orders:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['orders:orders:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange"
      @row-dblclick="handleView">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="采购时间" align="center" prop="orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="amount" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_orders_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300px">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="View" @click="handleView(scope.row)"
            v-hasPermi="['orders:orders:query']">查看</el-button> -->
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['orders:orders:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['orders:orders:remove']">删除</el-button>
          <el-button link type="primary" icon="Check" @click="handleOrderStatusChange(scope.row)"
            v-hasPermi="['orders:orders:edit']" v-if="scope.row.status === '1'">通过</el-button>
          <el-button link type="danger" icon="Close" @click="handleOrderStatusChange(scope.row, '3')"
            v-hasPermi="['orders:orders:edit']" v-if="scope.row.status === '1'">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改药品采购订单对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="主键id" prop="id">
          <el-input v-model="form.id" placeholder="请输入主键id" />
        </el-form-item>
        <el-form-item label="采购时间" prop="orderTime">
          <el-date-picker clearable
            v-model="form.orderTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择采购时间">
          </el-date-picker>
        </el-form-item> -->

        <el-divider content-position="center">采购订单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddOrderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteOrderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="orderDetailList" :row-class-name="rowOrderDetailIndex"
          @selection-change="handleOrderDetailSelectionChange" ref="orderDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="药品名称" prop="medicationId" width="220">
            <template #default="scope">
              <el-select v-model="scope.row.medicationId" placeholder="请选择药品"
                @change="handleMedicationChange(scope.row)" clearable>
                <el-option v-for="item in medicationOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="供应商名称" prop="supplierId" width="220">
            <template #default="scope">
              <el-select v-model="scope.row.supplierId" placeholder="请选择供应商" @change="handleSupplierChange(scope.row)"
                clearable :disabled="!scope.row.medicationId">
                <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="采购数量" prop="quantity" width="150">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" placeholder="请输入采购数量" :min="1"
                @change="handleQuantityChange(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.price" placeholder="自动获取单价" disabled />
            </template>
          </el-table-column>
          <el-table-column label="总金额" prop="totalAmount" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.totalAmount" placeholder="自动计算总金额" disabled />
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="总金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入总金额" disabled />
        </el-form-item>
        <!-- <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态，1 申请中，2 已完成，3 未通过">
            <el-option v-for="dict in sys_orders_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看药品采购订单详细对话框 -->
    <el-dialog title="查看药品采购订单详细对话框" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="主键id">{{
          viewForm.id
          }}</el-descriptions-item>
        <el-descriptions-item label="采购时间">{{
          parseTime(viewForm.orderTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="总金额">{{
          viewForm.amount
          }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          parseTime(viewForm.createTime)
          }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="sys_orders_status" :value="viewForm.status" />
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">采购订单明细信息</el-divider>
      <el-table :data="viewForm.orderDetailList">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="药品id" prop="medicationId" align="center" />
        <el-table-column label="供应商id" prop="supplierId" align="center" />
        <el-table-column label="采购数量" prop="quantity" align="center" />
        <el-table-column label="单价" prop="price" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders, getMedicationPrice } from "@/api/orders/orders";
import { listMedication } from "@/api/medication/medication";
import { listSupplier } from "@/api/supplier/supplier";

const { proxy } = getCurrentInstance();
const { sys_orders_status } = proxy.useDict('sys_orders_status');

const ordersList = ref([]);
const orderDetailList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedOrderDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeStatus = ref("");
const viewForm = ref({});
const medicationOptions = ref([]);
const supplierOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    orderTime: null,
    amount: null,
    createTime: null,
    status: null
  },
  rules: {
    status: [
      { required: true, message: "订单状态，1 申请中，2 已完成，3 未通过不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 状态切换 */
function handleStatusChange(tab) {
  queryParams.value.status = tab.props.name;
  queryParams.value.pageNum = 1;
  getList();
}

/** 查询药品采购订单列表 */
function getList() {
  loading.value = true;
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderTime: null,
    amount: null,
    createTime: null,
    status: null
  };
  orderDetailList.value = [];
  proxy.resetForm("ordersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加药品采购订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = response.data;
    orderDetailList.value = response.data.orderDetailList;
    open.value = true;
    title.value = "修改药品采购订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      form.value.orderDetailList = orderDetailList.value;
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除药品采购订单编号为"' + _ids + '"的数据项？').then(function () {
    return delOrders(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 采购订单明细序号 */
function rowOrderDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 采购订单明细添加按钮操作 */
function handleAddOrderDetail() {
  let obj = {
    medicationId: undefined,
    medicationName: undefined,
    productCode: undefined,
    supplierId: undefined,
    supplierName: undefined,
    quantity: undefined,
    price: undefined,
    totalAmount: undefined
  };
  orderDetailList.value.push(obj);
}

/** 采购订单明细删除按钮操作 */
function handleDeleteOrderDetail() {
  if (checkedOrderDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的采购订单明细数据");
  } else {
    const orderDetails = orderDetailList.value;
    const checkedOrderDetails = checkedOrderDetail.value;
    orderDetailList.value = orderDetails.filter(function (item) {
      return checkedOrderDetails.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleOrderDetailSelectionChange(selection) {
  checkedOrderDetail.value = selection.map(item => item.index)
}

/** 查看按钮操作 */
function handleView(row) {
  getOrders(row.id).then((response) => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orders/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

/** 获取药品列表 */
function getMedicationList() {
  loading.value = true;
  listMedication({
    pageSize: 100
  }).then(response => {
    console.log('Raw medication response:', response);
    if (response && response.rows) {
      medicationOptions.value = response.rows
        .filter(item => item && item.id && item.number)
        .map(item => ({
          medicationId: item.id,
          number: item.number,
          value: item.id,
          label: `${item.name} (${item.number})`,
          name: item.name
        }));
      console.log('Processed medication options:', medicationOptions.value);
    } else {
      proxy.$modal.msgError("获取药品列表失败");
    }
  }).catch(error => {
    proxy.$modal.msgError("获取药品列表失败");
    console.error('Error getting medication list:', error);
  }).finally(() => {
    loading.value = false;
  });
}

/** 获取供应商列表 */
function getSupplierList(productCode) {
  loading.value = true;
  console.log('Fetching suppliers for product code:', productCode);
  listSupplier({
    pageSize: 100,
    productCode: productCode
  }).then(response => {
    console.log('Raw supplier response:', response);
    if (response && response.rows) {
      supplierOptions.value = response.rows
        .filter(item => item && item.id)
        .map(item => ({
          supplierId: item.id,
          value: item.id,
          label: item.name,
          name: item.name
        }));
      console.log('Processed supplier options:', supplierOptions.value);
      if (supplierOptions.value.length === 0) {
        proxy.$modal.msgWarning("未找到提供该药品的供应商");
      }
    } else {
      proxy.$modal.msgError("获取供应商列表失败");
    }
  }).catch(error => {
    proxy.$modal.msgError("获取供应商列表失败");
    console.error('Error getting supplier list:', error);
  }).finally(() => {
    loading.value = false;
  });
}

/** 计算总金额 */
function calculateTotalAmount(row) {
  if (row.quantity && row.price) {
    row.totalAmount = (parseFloat(row.quantity) * parseFloat(row.price)).toFixed(2);
    // 更新订单总金额
    form.value.amount = orderDetailList.value.reduce((sum, detail) => {
      return sum + (detail.totalAmount ? parseFloat(detail.totalAmount) : 0);
    }, 0).toFixed(2);
  }
}

/** 处理药品选择变化 */
async function handleMedicationChange(row) {
  console.log('Medication changed:', row);
  if (row.medicationId) {
    const selectedMedication = medicationOptions.value.find(item => item.value === row.medicationId);
    console.log('Selected medication:', selectedMedication);
    if (selectedMedication) {
      row.medicationName = selectedMedication.name;
      row.productCode = selectedMedication.number;
      console.log('Product code for supplier search:', row.productCode);
      // 清空供应商相关信息
      row.supplierId = undefined;
      row.supplierName = undefined;
      row.price = undefined;
      row.totalAmount = undefined;
      // 获取该药品对应的供应商列表
      getSupplierList(selectedMedication.number);
      calculateTotalAmount(row);
    }
  } else {
    row.medicationName = undefined;
    row.productCode = undefined;
    row.supplierId = undefined;
    row.supplierName = undefined;
    row.price = undefined;
    row.totalAmount = undefined;
    // 清空供应商列表
    supplierOptions.value = [];
    calculateTotalAmount(row);
  }
}

/** 处理供应商选择变化 */
async function handleSupplierChange(row) {
  console.log('Supplier changed:', row);
  if (row.supplierId && row.medicationId) {
    const selectedSupplier = supplierOptions.value.find(item => item.value === row.supplierId);
    console.log('Selected supplier:', selectedSupplier);
    if (selectedSupplier) {
      row.supplierId = selectedSupplier.supplierId;
      row.supplierName = selectedSupplier.name;
      try {
        console.log('Fetching price with:', {
          medicationId: row.medicationId,
          supplierId: row.supplierId
        });
        const res = await getMedicationPrice(row.medicationId, row.supplierId);
        console.log('Price response:', res);
        if (res.code === 200) {
          row.price = res.data;
          calculateTotalAmount(row);
        } else {
          proxy.$modal.msgError(res.msg || "获取药品单价失败");
        }
      } catch (error) {
        console.error("获取药品单价失败:", error);
        proxy.$modal.msgError("获取药品单价失败");
      }
    }
  } else {
    row.supplierId = undefined;
    row.supplierName = undefined;
    row.price = undefined;
    row.totalAmount = undefined;
    calculateTotalAmount(row);
  }
}

/** 处理数量变化 */
function handleQuantityChange(row) {
  calculateTotalAmount(row);
}

/** 处理状态变更 */
function handleOrderStatusChange(row, targetStatus) {
  const statusMap = {
    '1': '2', // 申请中 -> 已完成
    '2': '3', // 已完成 -> 未通过
    '3': '1'  // 未通过 -> 申请中
  };

  const newStatus = targetStatus || statusMap[row.status];
  const statusText = {
    '1': '申请中',
    '2': '已完成',
    '3': '未通过'
  };

  proxy.$modal.confirm(`是否确认将订单状态变更为"${statusText[newStatus]}"？`).then(function () {
    return updateOrders({
      ...row,
      status: newStatus
    });
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("状态变更成功");
  }).catch(() => { });
}

getList();
getMedicationList();
</script>
<style scoped>
.el-tabs {
  margin-bottom: 20px;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style>